<template>
  <div class="score-detail">
    <div v-if="init">
      <a-skeleton active/>
    </div>
    <div v-else>
      <!-- Tab栏 -->
      <a-button class="content-nav-btn content-nav-left" @click="prevDirectory">
        <LeftOutlined/>
      </a-button>
      <a-button class="content-nav-btn content-nav-right" @click="nextDirectory"
      >
        <RightOutlined/>
      </a-button>
      <div class="title-container">
        <div class="tabs-wrapper">
          <div class="tabs">
            <div v-for="(item,index) of tabKeys" :key="index" :class="['tab', activeTab === item ? 'active':'normal']"
                 @click="activeTab = item">
              <div class="span">{{ item }} (得分: {{ getTabScore(item) }})</div>
            </div>
          </div>
        </div>
        <a-button type="primary" class="btn-save" :loading="submitLoading" @click="onSave">保存</a-button>
      </div>

      <!-- 内容区 -->
      <div class="content">
        <!-- 评分区 -->
        <div class="score-section" v-if="currentDirectoryItem" ref="scoreSectionRef">
          <div class="title-row">
            <span class="title">{{ currentDirectoryItem.title }}</span>
            <span class="detail-link" @click="currentDirectoryItem.showDetail = !currentDirectoryItem.showDetail">
            详细说明
            <DownOutlined v-if="!currentDirectoryItem.showDetail"></DownOutlined>
            <UpOutlined v-else></UpOutlined>
          </span>
          </div>
          <div v-if="!currentDirectoryItem.showDetail" class="detail-section">
            <div v-html="currentDirectoryItem.sketchDesc" class="html"></div>
            <!--            <div class="detail-note">紧急订单需要取得公司批准工作方可进行。</div>-->
          </div>
          <div>
            <div class="desc">
              <span class="green">计算方式：延误/失误1次扣5分，最多扣10分。</span>
            </div>
            <div class="input-row">
              <div class="input-label">自评分数（最大:）+{{ currentDirectoryItem.maxQuantity }}</div>
              <a-input-number v-model:value="currentDirectoryItem.quantity" :max="currentDirectoryItem.maxQuantity"
                              :min="0" :disabled="!isSelf"></a-input-number>
            </div>
            <div class="input-row">
              <div class="input-label">自评说明</div>
              <a-textarea placeholder="请对该自己工作做出评价" :disabled="!isSelf"
                          v-model:value="currentDirectoryItem.description">
              </a-textarea>
            </div>
            <div class="input-row" v-if="!isSelf">
              <div class="input-label">评审分数（最大:）+{{ currentDirectoryItem.maxQuantity }}</div>
              <a-input-number v-model:value="currentDirectoryItem.quantityLead" :max="currentDirectoryItem.maxQuantity"
                              :min="0"></a-input-number>
            </div>
            <div class="input-row" v-if="!isSelf">
              <div class="input-label">评审说明</div>
              <a-textarea placeholder="请对该同事工作做出评价"
                          v-model:value="currentDirectoryItem.descriptionLead"></a-textarea>
            </div>
          </div>
        </div>

        <!-- 底部目录栏 -->
        <div class="bottom-directory" v-if="!init">
          <swiper
              :modules="modules"
              :slidesPerView="swiperSize"
              :centeredSlides="showCenter"
              :loop="true"
              :spaceBetween="20"
              :style="{ width: '100%', margin: '0 auto' }"
              @swiper="setSwiperRef"
          >
            <swiper-slide
                v-for="(item, index) in directoryItems"
                :key="index"
                @click="selectDirectoryItem(item)"
                :class="['directory-item', isCurrentDirectoryItem(item) ? 'active' : '']"
                style="display: flex;justify-content: center"
            >
              {{ item.title }} ({{ item.score }})
            </swiper-slide>
          </swiper>
        </div>
      </div>
    </div>


  </div>
</template>

<script>
import {ref} from 'vue'
import {UpOutlined, DownOutlined, LeftOutlined, RightOutlined} from "@ant-design/icons-vue"
import help from "@/utils/help.js";
import api from "@/api/index.js";
import dayjs from "dayjs";
import {message} from "ant-design-vue";
import {useUserInfoStore} from "@/stores/userInfo.js";
import {Swiper, SwiperSlide} from 'swiper/vue';
import 'swiper/css'
import 'swiper/css/pagination'
import 'swiper/css/navigation'
import {Pagination, Navigation} from 'swiper/modules'

export default {
  components: {
    UpOutlined, DownOutlined, LeftOutlined, RightOutlined,
    Swiper, SwiperSlide
  },
  props: ["userId", "dataDate", "isSelf"],
  data() {
    return {
      activeTab: null,
      init: false,
      tabKeys: [],
      dataMap: {},
      submitLoading: false,
      currentTabIndex: 0,
      currentDirIndex: 0,
      directoryItems: [],
      scoreSectionRef: null,
      modules: [Pagination, Navigation],
      swiperRef: null,
    }
  },
  mounted() {
    this.getDetail()
  },
  computed: {
    swiperSize() {
      return Math.min(this.directoryItems.length, 5)
    },
    showCenter() {
      return Math.min(this.directoryItems.length, 5) >= 5
    },

    swiperLength() {
      return this.directoryItems.length > 5 ? 5 : this.directoryItems.length;
    },
    swiperWidth() {
      const slideWidth = 120;
      const space = 20;
      const count = Math.min(this.directoryItems.length, 5); // 视口最多显示5条
      return count * slideWidth + (count - 1) * space;
    },
    tabDetail() {
      if (!this.activeTab) {
        return []
      } else {
        return this.dataMap[this.activeTab] || [];
      }
    },
    currentDirectoryItem() {
      if (!this.directoryItems || this.directoryItems.length === 0) {
        return null;
      }
      return this.directoryItems[this.currentDirIndex] || null;
    }
  },
  watch: {
    activeTab(newTab) {
      this.currentTabIndex = this.tabKeys.indexOf(newTab);
      this.updateDirectoryItems();
    }
  },
  methods: {
    showTitle(sketch) {
      if (sketch) {
        return sketch.split("-")[1] || ""
      } else {
        return ""
      }
    },
    async getDetail() {
      this.init = true;
      try {
        let result = await api.getSalaryPerformances({
          userId: this.userId,
          dataDate: dayjs(this.dataDate).format("YYYY-MM-DD"),
        })
        let map = this.groupBySketch(result);
        this.dataMap = map;
        this.tabKeys = this.getSortedKeysByChinese(map);
        this.activeTab = this.tabKeys[0];
        this.currentTabIndex = 0;
        this.updateDirectoryItems();
        console.log("map", map)
      } catch (error) {
        help.showError(error);
      } finally {
        this.init = false;
      }
    },
    groupBySketch(data) {
      return data.reduce((acc, item) => {
        if (!item.sketch) return acc;

        // 以 - 分割，取前半部分作为 key
        const [category] = item.sketch.split('-');

        if (!acc[category]) {
          acc[category] = [];
        }
        let newItem = {
          ...item,
          "matchingID": item.matchingId,
          "dataDate": dayjs(item.dataDate).format("YYYY-MM-DD"),
        }
        acc[category].push(newItem);

        return acc;
      }, {});
    },
    getSortedKeysByChinese(obj) {
      return Object.keys(obj).sort((a, b) => a.localeCompare(b, 'zh-CN'));
    },

    // Tab切换相关方法
    prevTab() {
      if (this.currentTabIndex > 0) {
        this.currentTabIndex--;
        this.activeTab = this.tabKeys[this.currentTabIndex];
      }
    },

    nextTab() {
      if (this.currentTabIndex < this.tabKeys.length - 1) {
        this.currentTabIndex++;
        this.activeTab = this.tabKeys[this.currentTabIndex];
      }
    },

    getTabScore(tabKey) {
      const items = this.dataMap[tabKey] || [];
      if (items.length === 0) return 0;
      const totalScore = items.reduce((sum, item) => {
        return sum + (this.isSelf ? (item.quantity || 0) : (item.quantityLead || 0));
      }, 0);
      return totalScore;
    },

    // 目录栏相关方法
    updateDirectoryItems() {
      if (!this.activeTab || !this.dataMap[this.activeTab]) {
        this.directoryItems = [];
        this.currentDirIndex = 0;
        return;
      }

      const items = this.dataMap[this.activeTab];
      this.directoryItems = items.map(item => {
        const title = this.showTitle(item.sketch);
        const score = this.isSelf ? (item.quantity || 0) : (item.quantityLead || 0);
        return {
          ...item, // 包含所有原始数据
          title: title || '其他项目',
          score: score,
        };
      });

      this.currentDirIndex = 0; // 重置为第一个项目

      // DOM 更新后，同步 Swiper 定位与卡片视图
      this.$nextTick(() => {
        if (this.swiperRef) {
          const slideTo = this.swiperRef.slideToLoop || this.swiperRef.slideTo;
          slideTo.call(this.swiperRef, this.currentDirIndex, 0);
        }
        this.scrollToActiveCard();
      });
    },

    isCurrentDirectoryItem(item) {
      // 检查当前显示的内容是否与目录项匹配
      if (!this.directoryItems || this.directoryItems.length === 0) return false;
      return this.directoryItems[this.currentDirIndex] && this.directoryItems[this.currentDirIndex].sketch === item.sketch;
    },

    selectDirectoryItem(item) {
      // 点击目录项时，切换到对应的索引
      const index = this.directoryItems.findIndex(dirItem => dirItem.sketch === item.sketch);
      if (index !== -1) {
        this.currentDirIndex = index;
        if (this.swiperRef) {
          const slideTo = this.swiperRef.slideToLoop || this.swiperRef.slideTo;
          slideTo.call(this.swiperRef, this.currentDirIndex, 300);
        }
        this.scrollToActiveCard();
      }
    },


    scrollToActiveCard() {
      this.$nextTick(() => {
        if (this.scoreSectionRef) {
          const card = this.scoreSectionRef;

          // 获取卡片相对于视口的位置
          const cardRect = card.getBoundingClientRect();
          const viewportHeight = window.innerHeight;
          const cardHeight = cardRect.height;

          // 计算需要滚动的距离，使卡片在视口中央
          const scrollTop = window.pageYOffset + cardRect.top - (viewportHeight / 2) + (cardHeight / 2);

          // 平滑滚动到目标位置
          window.scrollTo({
            top: Math.max(0, scrollTop),
            behavior: 'smooth'
          });
        }
      });
    },

    prevDirectory() {
      if (!this.directoryItems || this.directoryItems.length === 0) return;

      // Swiper 循环优先
      if (this.swiperRef && typeof this.swiperRef.slidePrev === 'function') {
        this.swiperRef.slidePrev(300);
      }

      // 索引首尾环绕
      if (this.currentDirIndex > 0) {
        this.currentDirIndex--;
      } else {
        this.currentDirIndex = this.directoryItems.length - 1;
      }

      // 同步定位
      if (this.swiperRef && !(typeof this.swiperRef.slidePrev === 'function')) {
        const slideTo = this.swiperRef.slideToLoop || this.swiperRef.slideTo;
        slideTo.call(this.swiperRef, this.currentDirIndex, 300);
      }
      // this.scrollToActiveCard();
    },

    nextDirectory() {
      if (!this.directoryItems || this.directoryItems.length === 0) return;

      // Swiper 循环优先
      if (this.swiperRef && typeof this.swiperRef.slideNext === 'function') {
        this.swiperRef.slideNext(300);
      }

      // 索引首尾环绕
      if (this.currentDirIndex < this.directoryItems.length - 1) {
        this.currentDirIndex++;
      } else {
        this.currentDirIndex = 0;
      }

      // 同步定位
      if (this.swiperRef && !(typeof this.swiperRef.slideNext === 'function')) {
        const slideTo = this.swiperRef.slideToLoop || this.swiperRef.slideTo;
        slideTo.call(this.swiperRef, this.currentDirIndex, 300);
      }
      // this.scrollToActiveCard();
    },

    async onSave() {
      this.submitLoading = true;
      if (this.isSelf) {
        for (let i = 0; i < this.tabKeys.length; i++) {
          let key = this.tabKeys[i];
          await this.putSalaryPerformances(key, this.dataMap[key].map((item) => {
            return {
              "matchingID": item.matchingID,
              "dataDate": item.dataDate,
              "quantity": item.quantity,
              "description": item.description,
            }
          }));
        }
      } else {
        for (let i = 0; i < this.tabKeys.length; i++) {
          let key = this.tabKeys[i];
          let userInfoStore = useUserInfoStore();
          await this.AuditSalaryPerformances(key, this.dataMap[key].map((item) => {
            return {
              "userId": userInfoStore.userId,
              "matchingId": item.matchingId,
              "dataDate": item.dataDate,
              "quantityAudit": item.quantityLead,
              "descriptionAudit": item.descriptionLead
            }
          }));
        }
      }
      // 更新目录项数据
      this.updateDirectoryItems();
      this.submitLoading = false;
    },

    async AuditSalaryPerformances(key, params) {
      try {
        await api.auditSalaryPerformances(params);
        message.success(key + "保存成功");
      } catch (error) {
        help.showError(key + error.toString());
      }
    },

    async putSalaryPerformances(key, params) {
      try {
        await api.putSalaryPerformances(params);
        message.success(key + "保存成功");
      } catch (error) {
        help.showError(key + error.toString());
      }
    },
    setSwiperRef(swiper) {
      this.swiperRef = swiper;
    },
    slideTo(index) {
      if (this.swiperRef) {
        this.swiperRef.slideTo(index - 1, 0);
      }
    },
  }
}

</script>

<style lang="less" scoped>

.score-detail {
  padding: 10px 0;
  display: flex;
  width: 100%;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #fff;

  .title-container {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    padding: 0 24px 10px;
    border-bottom: 1px solid #eee;
    position: relative;
  }

  .tabs-wrapper {
    display: flex;
    align-items: center;
    flex: 1;
    gap: 8px;
  }

  .tab-nav-btn {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #d9d9d9;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    z-index: 10;

    position: absolute;
    top: 50%;
    transform: translateY(-50%);

    &:hover:not(:disabled) {
      border-color: #3a8c3a;
      color: #3a8c3a;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }

  .btn-save {
    width: 100px;
    background-color: #2e5e45;
    border-radius: 10px;
    margin-left: 10px;
  }

  .tabs {
    display: flex;
    border-radius: 16px;
    position: relative;
    overflow: hidden;
    flex: 1;

    .tab {
      flex: 1;
      text-align: center;
      background: #e5e6e9;
      color: rgba(0, 0, 0, 0.2);
      font-weight: 500;
      cursor: pointer;


      &.active {
        div {
          color: #3a8c3a;
          border-bottom: 4px solid #3a8c3a;
          padding: 8px 20px;
          display: inline-block;
          margin: 0;
        }
      }

      &.normal {
        div {
          padding: 8px 20px;
          display: inline-block;
          margin: 0;
        }
      }


      &:last-child {
        margin-right: 0;
      }
    }
  }

  .content {
    border-radius: 12px;
    padding: 0px 32px;
    position: relative;

    .score-section {
      margin-bottom: 20px;

      .title-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .title {
          font-size: 24px;
          font-weight: bold;
          margin-right: 16px;
        }

        .detail-link {
          color: #888;
          cursor: pointer;
          font-size: 12px;
        }
      }

      .desc {
        margin: 0px 0 12px;

        .green {
          color: #3a8c3a;
        }
      }

      .score-row {
        display: flex;
        gap: 12px;
        flex-direction: column;
        margin-left: 1em;

        .score-item {
          display: flex;
          align-items: center;
          gap: 8px;

          .stars {
            .star {
              font-size: 20px;
              color: #ffd700;

              &.filled {
                color: #ffd700;
              }

              &.red {
                color: #e74c3c;
              }
            }
          }
        }
      }

      .input-row {
        margin: 12px 0;

        p {
          font-size: 14px;
          color: #888;
          margin-top: 16px;
        }

        .input-label {
          font-weight: 600;
          margin-bottom: 4px;
        }

        .input, .textarea {
          width: 100%;
          border: 1px solid #ccc;
          border-radius: 6px;
          padding: 8px;
          font-size: 14px;
          margin-top: 4px;
        }

        .textarea {
          min-height: 80px;
          resize: vertical;
        }
      }
    }

    .detail-section {
      margin-top: 20px;

      ol {
        color: rgba(0, 0, 0, 0.25);
        padding: 0 14px;
      }

      .detail-note {
        color: rgba(0, 0, 0, 0.25);
        margin: 8px 0 20px;
      }

      .desc.green {
        color: #3a8c3a;
      }
    }
  }

  .content-nav-btn {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #d9d9d9;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    z-index: 10;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);

    &:hover:not(:disabled) {
      border-color: #3a8c3a;
      color: #3a8c3a;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    &.content-nav-left {
      left: -16px;
    }

    &.content-nav-right {
      right: 32px;
    }
  }
}

.html {
  color: rgba(0, 0, 0, 0.6);
  line-height: 1.5;
  margin-bottom: 20px;
}

.line {
  width: calc(100% + 48px);
  height: 1px;
  background-color: rgba(0, 0, 0, 0.2);
  margin: 0 -24px
}

.bottom-directory {
  position: relative;
  background: #fff;
  border-radius: 16px;
  padding: 16px 0px;
  margin-top: 24px;
  display: flex;
  align-items: center;

  .directory-items {
    display: flex;
    overflow-x: auto;
    flex: 1;
    padding: 4px 0;
    justify-content: flex-start;
    flex-wrap: nowrap;
    scroll-behavior: smooth;

    /* 隐藏滚动条 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */

    &::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera */
    }
  }

  .directory-item {
    white-space: nowrap;
    padding: 8px 16px;
    border-radius: 20px;
    background: transparent;
    border: none;
    cursor: pointer;
    font-size: 14px;
    color: #999;
    transition: all 0.3s ease;
    flex-shrink: 0;
    font-weight: 400;

    &:hover {
      color: #3a8c3a;
    }

    &.active {
      background: transparent;
      color: #3a8c3a;
      border: none;
      font-weight: 600;
    }
  }
}
</style>